package com.moose.operator.web.service.impl.im;

import com.corundumstudio.socketio.SocketIOClient;
import com.moose.operator.common.SnowflakeIdWorker;
import com.moose.operator.constant.ChatConstant;
import com.moose.operator.mapper.MessageRecordMapper;
import com.moose.operator.model.domain.message.MessageRecordDO;
import com.moose.operator.model.template.MessageTemplate;
import com.moose.operator.socket.io.MessageUtils;
import com.moose.operator.socket.io.SocketConnection;
import com.moose.operator.util.MapperUtils;
import com.moose.operator.web.service.SingleMessageService;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author taohua
 * @version v1.0.0
 * @date 2021-02-05 09:53:09:53
 * @see com.moose.operator.web.service.impl.im
 */
@Slf4j
@Service
public class SingleMessageServiceImpl implements SingleMessageService {

  @Resource
  private SocketConnection socketConnection;

  @Resource
  private SnowflakeIdWorker snowflakeIdWorker;

  @Resource
  private MessageRecordMapper messageRecordMapper;

  @Override public void saveMessage(MessageTemplate template) {

    // TODO： 消息 ack
    MessageRecordDO messageRecord = null;
    try {
      // mock
      //String fromUserId = template.getFromUserId();
      //SocketIOClient fromSocket = socketIOClientMap.get(fromUserId);
      //if ("786600935907659776".equals(toUserId)) {
      //  if (null != fromSocket && fromSocket.isChannelOpen()) {
      //    fromSocket.sendEvent(ChatConstant.SINGLE_CHAT, "你们不是好友！！");
      //  }
      //  return;
      //}

      //log.info("{}", request);

      // 检查 消息模版 参数 ...

      // 判断用户是否存在 ...

      // 是否是好友 ...

      /////////////////////////// save message record ///////////////////////////

      // 发送者ID
      Long sendId = template.getSendId();

      // 接受者 ID
      Long receiveId = template.getReceiveId();

      // 构建消息
      messageRecord = new MessageRecordDO();
      messageRecord.setMsgId(snowflakeIdWorker.nextId());
      messageRecord.setSendId(sendId);
      messageRecord.setReceiveId(receiveId);
      messageRecord.setContent(template.getContent());
      messageRecord.setType(MessageUtils.convertType(template.getType()));
      messageRecord.setChatType(MessageUtils.convertChatType(template.getChatType()));
      // 保存消息
      messageRecordMapper.insertMessageRecord(messageRecord);

      // TODO: 消息传输过程失败情况

      // TODO: 并发情况
      // 发送消息
      // 判断是否在线
      SocketIOClient receiveSocket = socketConnection.getSocketIOClient(String.valueOf(receiveId));
      if (null != receiveSocket && receiveSocket.isChannelOpen()) {
        // 客户端监听单聊事件
        receiveSocket.sendEvent(ChatConstant.SINGLE_CHAT, MapperUtils.obj2json(template));
        // TODO: un read count compute --> 0
        // messageRecord.setUnReadCount(0);
      } else {
        // TODO: un read count compute --> redis increment or decrement
        // messageRecord.setUnReadCount(0);
      }
    } catch (Exception exception) {
      exception.printStackTrace();
      log.info("消息解析: 错误 [{}] 消息 [{}]", exception.getMessage(), template);
    }
  }
}
